<?php

namespace app\admin\controller\excourse;

use app\admin\controller\Zlog;
use app\admin\model\excourse\Orgcate;
use app\common\controller\Backend;
use think\Cache;
use think\Db;
use think\Exception;

/**
 * 课程
 *
 * @icon fa fa-circle-o
 */
class Orgcourse extends Backend
{
    
    /**
     * Course模型对象
     * @var \app\admin\model\learn\Course
     */
    protected $model = null;
    protected $searchFields = 'course.name';
    protected $org_cate_id = 0;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\learn\Course;
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("isBuyList", $this->model->getIsBuyList());
//        $where2 = $this->getSelfDataWhere('org_cate_id');
        $orgcatelList = collection(Orgcate::where(true)->select())->toArray();
        $orgcatedata = array();
        if($orgcatelList){
            foreach($orgcatelList  as $key => $val){
                if($key == 0){
                    $this->org_cate_id = $val['org_cate_id'];
                }
                $orgcatedata[$val['org_cate_id']] = $val['org_cate_name'];
            }
        }
        $this->view->assign("orgcatedata", $orgcatedata);
    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $filter = $this->request->get("filter", '');
            $filter = (array)json_decode($filter, true);
            if(isset($filter['org_cate_id']) && $filter['org_cate_id'] > 0){
                $this->org_cate_id = $filter['org_cate_id'];
            }
            $data = Db::name('org_cate_excourse')->where('org_cate_id', $this->org_cate_id)->find();
            if($this->org_cate_id <= 0 || empty($data)){
                $result = array("total" => 0, "rows" => array());
                return json($result);
            }

//            $where2 = $this->getSelfDataWhere('course.org_cate_id');
            $total = $this->model
                    ->with(['teacher','admin'])
//                ->where($where2)
//                    ->where($where)
                    ->where(['course.org_cate_id'=>0])
                    ->order($sort, $order)
                    ->count();
            $list = $this->model
                ->with(['teacher','admin'])
                ->where(['course.org_cate_id'=>0])
//                    ->where($where)
//                    ->where($where2)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();

            foreach ($list as $row) {
                $row->start_time = $data['start_time'];
                $row->end_time = $data['end_time'];
//                $row->visible(['id','name','origin_price','price','visitor_origin_price','visitor_price','buy_numbers','image','thumbs','is_buy','status','createtime']);
                
            }
            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }
    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                Db::startTrans();
                try{
                    $cate_data = array();
                    $special_data = array();
                    $cate_ids = isset($params['learn_cate_ids'])?$params['learn_cate_ids']:array();
                    $special_ids = isset($params['learn_special_ids'])?$params['learn_special_ids']:array();
                    if($cate_ids){
                        $i= 0;
                        foreach($cate_ids as $k=>$val){
                            if(isset($params['type'.$val]) && !empty($params['type'.$val])){
                                foreach($params['type'.$val] as $v){
                                    $cate_data[$i]['learn_cate_id'] = $val;
                                    $cate_data[$i]['type'] = $v;
                                    $cate_data[$i]['org_cate_id'] = ORG_CATE_ID;
                                    $cate_data[$i]['createtime'] = time();
                                    $i++;
                                }
                            }
                        }
                    }
                    if($special_ids){
                        foreach($special_ids as $k=>$val){
                            $special_data[$k]['learn_special_id'] = $val;
                            $special_data[$k]['org_cate_id'] = ORG_CATE_ID;
                            $special_data[$k]['createtime'] = time();
                        }
                    }
                    unset($params['learn_cate_ids']);
                    unset($params['type1']);
                    unset($params['type2']);
                    unset($params['type3']);
                    unset($params['learn_special_ids']);
                    $params['org_cate_id'] = ORG_CATE_ID;
                    $params['createtime'] = time();
                    $params['adminid'] = AID;
                    $index = 6 -strlen($params['number']) ;
                    if($index > 0){
                        for($i=0;$i<$index;$i++){
                            $params['number'] = '0'.$params['number'];
                        }
                    }
                    $total = $this->model->where('number', $params['number'])->count();
                    if($total > 0){
                        $this->error('课程编码已存在！');
                    }
                    if(ORG_CATE_ID > 0){
                        $params['type'] = 2;
                    }else{
                        $params['type'] = 1;
                    }
//                $params['author'] = str_replace('，', ',', $params['author']);
                    $result = $this->model->validate()->insertGetId($params);

                    if ($result === false) {
                        $this->error($this->model->getError());
                    }
                    if($cate_data){
                        foreach($cate_data as &$v){
                            $v['learn_course_id'] = $result;
                        }
                        Db::name('learn_cate_course1')->insertAll($cate_data);
                    }
                    if($special_data){
                        foreach($special_data as &$va){
                            $va['learn_course_id'] = $result;
                        }
                        Db::name('learn_cate_course3')->insertAll($special_data);
                    }
                    Db::commit();
                }catch (Exception $e){
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                $this->success();
            }
            $this->error();
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row= $this->model->get(['id' => $ids]);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {

                Db::startTrans();
                try{
                    $cate_data = array();
                    $special_data = array();
                    $cate_ids = isset($params['learn_cate_ids'])?$params['learn_cate_ids']:array();
                    $special_ids = isset($params['learn_special_ids'])?$params['learn_special_ids']:array();
                    if($cate_ids){
                        $i= 0;
                        foreach($cate_ids as $k=>$val){
                            if(isset($params['type'.$val]) && !empty($params['type'.$val])){
                                foreach($params['type'.$val] as $v){
                                    $cate_data[$i]['learn_course_id'] = $ids;
                                    $cate_data[$i]['learn_cate_id'] = $val;
                                    $cate_data[$i]['type'] = $v;
                                    $cate_data[$i]['org_cate_id'] = ORG_CATE_ID;
                                    $cate_data[$i]['createtime'] = time();
                                    $i++;
                                }
                            }
                        }
                        Db::name('learn_cate_course1')->where('learn_course_id', $ids)->delete();
                        Db::name('learn_cate_course1')->insertAll($cate_data);
                    }
                    if($special_ids){
                        foreach($special_ids as $k=>$val){
                            $special_data[$k]['learn_course_id'] = $ids;
                            $special_data[$k]['learn_special_id'] = $val;
                            $special_data[$k]['org_cate_id'] = ORG_CATE_ID;
                            $special_data[$k]['createtime'] = time();
                        }
                        Db::name('learn_cate_course3')->where('learn_course_id', $ids)->delete();
                        Db::name('learn_cate_course3')->insertAll($special_data);

                    }
                    unset($params['learn_cate_ids']);
                    unset($params['type1']);
                    unset($params['type2']);
                    unset($params['type3']);
                    unset($params['learn_special_ids']);
                    $params['org_cate_id'] = ORG_CATE_ID;
                    $index = 6 -strlen($params['number']) ;
                    if($index > 0){
                        for($i=0;$i<$index;$i++){
                            $params['number'] = '0'.$params['number'];
                        }
                    }
                    $total = $this->model->where('number', $params['number'])->where('id','<>', $ids)->count();
                    if($total > 0){
                        $this->error('课程编码已存在！');
                    }
//                $params['author'] = str_replace('，', ',', $params['author']);
                    $result = $row->validate()->save($params);
                    if ($result === false) {
                        $this->error($row->getError());
                    }
                    Db::commit();
                }catch (Exception $e){
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                $this->success();
            }
            $this->error();
        }
        $learn_cate_data = Db::name('learn_cate_course1')->field('learn_cate_id,type')->where('learn_course_id', $ids)->select();
        $type_arr = array('type1'=>[],'type2'=>[],'type3'=>[]);
        $learn_cate_ids = array();
        if($learn_cate_data){
            foreach($learn_cate_data as $val){
                $learn_cate_ids[] = $val['learn_cate_id'];
                $type_arr['type'.$val['learn_cate_id']][] = $val['type'];
            }
        }
        $learn_special_ids = Db::name('learn_cate_course3')->where('learn_course_id', $ids)->column('learn_special_id');
        $this->view->assign("row", $row);
        $this->view->assign("learn_special_ids", $learn_special_ids);
        $this->view->assign("type_arr", $type_arr);
        $this->view->assign("learn_cate_ids", $learn_cate_ids);
        return $this->view->fetch();
    }

    /*
     *总平台分配课程
     */
    public function sharecourse()
    {
        $this->view->assign("ids", $this->request->param('ids'));
        //当前是否为关联查询
        $this->relationSearch = false;
        $this->model = new \app\admin\model\org\Orgcate;
        $this->searchFields = 'id,name';
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->where($where)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    public function bindcourse($ids)
    {
        $this->model = new \app\admin\model\learn\Course;
        if ($this->request->isPost()) {
            $params = $this->request->post();
            if ($params) {
                if(isset($params['ids']) && !empty($params['ids'])){
                    $course = $this->model->getDataById($params['task_id']);
                    if($course){
                        $ids = explode(',', $params['ids']);
                        $data = [];
                        unset($course['id']);
                        foreach ($ids as $key=>$val){
                            $data[$key] = $course;
                            $data[$key]['org_cate_id'] = $val;
                            $data[$key]['is_buy'] = 1;
                            $data[$key]['createtime'] = time();
                        }
                        $result = $this->model->saveAll($data);
                        if ($result === false) {
                            $this->error($this->model->getError());
                        }
                        $this->success();
                    }

                }
                $this->error('课程编号错误！');
            }
            $this->error();
        }
        return $this->view->fetch();
    }
    /**
     * 查看章节
     */
    public function chapter()
    {
        $course_id = $this->request->param('ids');
        $this->view->assign("ids", $course_id);
        //当前是否为关联查询
        $this->relationSearch = false;
        $this->model = new \app\admin\model\learn\Chapter;
        $this->searchFields = 'id,name';
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $where2 = $this->getSelfDataWhere('org_cate_id');
            $total = $this->model
                ->where($where)
                ->where($where2)
                ->where(['edu_learn_course_id'=>$course_id])
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->where($where)
                ->where($where2)
                ->where(['edu_learn_course_id'=>$course_id])
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        return $this->view->fetch();
    }

    /*
     * 添加课程章节
     */
    public function chapteradd()
    {
        $course_id = $this->request->param('ids');
        $this->view->assign("ids", $course_id);
        $this->model = new \app\admin\model\learn\Chapter;
        if ($this->request->isPost()) {
            $row = $this->request->post("row/a", [], 'strip_tags');
            if ($row) {
                $total = $this->model->where('sort', '=', $row['sort'])->where('edu_learn_course_id', '=', $course_id)->count();
                if($total > 0){
                    $this->error('该课程章节序号【'.$row['sort'].'】已存在！');
                }
                if($course_id > 0){
                    $row['edu_learn_course_id'] = $course_id;
                    $row['org_cate_id'] = ORG_CATE_ID;
                    $row['createtime'] = time();
                    $res = $this->model->validate()->insertGetId($row);
                    if($res === false){
                        $this->error($this->model->getError());
                    }
                    $this->success();
                }
                $this->error('课程编号错误！');
            }
            $this->error('缺少必要参数！');
        }
        return $this->view->fetch();
    }

    /*
     * 编辑课程章节
     * @param null $ids
     * @return string
     */
    public function chapteredit($ids = null)
    {
        $this->model = new \app\admin\model\learn\Chapter;
        $row_data = $this->model->get(['id' => $ids]);
        if (!$row_data) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            $row = $this->request->post("row/a", [], 'strip_tags');
            if ($row) {
                if($ids > 0){
                    $result = $this->model->validate()->save($row,['id'=>$ids]);
                    if($result===false){
                        $this->error($this->model->getError());
                    }
                    $this->success();
                }
                $this->error('编号错误！');
            }
            $this->error('缺少必要参数！');
        }
        $this->view->assign("row", $row_data);
        return $this->view->fetch();
    }

    /*
     * 删除课程章节
     * @param null $ids
     */
    public function chapterdel($ids = null)
    {
        $this->model = new \app\admin\model\learn\Chapter;
        if ($ids) {
            $res = $this->model->where('id', 'in', $ids)->delete();
            if($res===false){
                $this->error($this->model->getError());
            }
            $this->success();
        }
        $this->error('编号错误！');
    }
}

